﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace Server
{
    class ChatService : MarshalByRefObject, IChatService
    {
        private List<string> _messages = new List<string>();
//        public event Action<string> Broadcast;
        private IBroadcast _broadcast;

        public List<string> GetRecentMessages()
        {
            List<string> resentMsgs;
            lock (_messages)
            {
                resentMsgs = (_messages as IEnumerable<string>).Reverse().Take(10).ToList();
            }
            return resentMsgs;
        }

        public void Talk(string ipAddr, string message)
        {
            _messages.Add(string.Format("[{0}]:{1}", ipAddr, message));
        }

//        public void Broadcasting(string message)
//        {
//            if (Broadcast != null)
//            {
//                Broadcast(message);
//            }
//        }

        public void SetBroadcast(IBroadcast broadcast)
        {
            _broadcast = broadcast;
        }

        public void SendBroadcastMessage(string message)
        {
            try
            {
                if (_broadcast != null)
                {
                    _broadcast.Send(message);
                }
            }
            catch (Exception)
            {
                _broadcast = null;
            }
        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}
